<!--src/views/cases/List.vue-->
<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import operateCaseApi from '@/api/operateCase'

const router = useRouter()
const props = defineProps({
  searchParams: {
    type: Object,
    default: () => ({})
  }
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const total = ref(0)
const pagination = reactive({
  page: 1,
  size: 10
})

// 案件状态选项
const statusOptions = [
  { label: '待受理', value: '1' },
  { label: '处理中', value: '2' },
  { label: '已完成', value: '3' },
  { label: '已取消', value: '4' },
  { label: '审核中', value: '5' },
  { label: '已通过', value: '6' },
  { label: '已拒绝', value: '7' }
]

// 案件类型选项
const caseTypeOptions = [
  { label: '民事案件', value: '1' },
  { label: '刑事案件', value: '2' },
  { label: '行政案件', value: '3' },
  { label: '其他案件', value: '4' }
]

// 获取案件列表
const fetchCases = async () => {
  loading.value = true
  try {
    // 确保从props.searchParams中正确解构参数
    const { caseName, status, caseType, dateRange } = props.searchParams

    const params = {
      caseName: caseName || undefined,
      status: status || undefined,
      caseType: caseType || undefined,
      dateRange: dateRange || undefined,
      page: pagination.page,
      size: pagination.size
    }

    // 移除undefined参数
    Object.keys(params).forEach(key => params[key] === undefined && delete params[key])

    console.log('API请求参数:', params) // 调试日志

    const res = await operateCaseApi.getCaseList(params)


    if (res.code === 200) {
      tableData.value = res.data.list
      total.value = res.data.pagination.total
    } else {
      const errorMessage = res.message || '获取案件列表失败'
      console.error(`[API Error] ${errorMessage}`, res)
      ElMessage.error(errorMessage)
    }
  } catch (error) {
    console.error('[Fetch Cases Error]', error)
    const errorMsg = error.response?.data?.message || error.message || '请求失败'
    ElMessage.error(`获取案件列表失败: ${errorMsg}`)
  } finally {
    loading.value = false
  }
}

// 搜索案件
const handleSearch = () => {
  pagination.page = 1
  fetchCases()
}

// 重置搜索
const handleReset = () => {
  pagination.page = 1
  fetchCases()
}

// 分页变化
const handlePaginationChange = () => {
  fetchCases()
}

// 查看详情
const viewDetail = (row) => {
  router.push(`/cases/detail/${row.id}`)
}

// 编辑案件
const editCase = (row) => {
  router.push({
    name: 'EditCase',
    params: { id: row.id },
    query: { from: 'list' }
  })
}

// 删除案件
const deleteCase = async (row) => {
  try {
    await ElMessageBox.confirm(
        `确定要删除案件 "${row.caseName}" 吗？此操作不可撤销！`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    loading.value = true
    const res = await caseAPI.deleteCase(row.id)

    if (res.code === 200) {
      ElMessage.success('删除成功')
      // 如果当前页只剩一条数据且不是第一页，则返回上一页
      if (tableData.value.length === 1 && pagination.page > 1) {
        pagination.page -= 1
      }
      fetchCases()
    } else {
      throw new Error(res.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除失败')
    }
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchCases()
})

// 修改watch监听方式
watch(() => ({ ...props.searchParams }), () => {
  handleSearch()
}, { immediate: true, deep: true })
</script>

<template>
  <div class="case-list-container">
    <el-card shadow="never">
      <el-table
          :data="tableData"
          border
          stripe
          v-loading="loading"
          style="width: 100%"
      >
        <el-table-column
            prop="caseName"
            label="案件名称"
            width="180"
        />
        <el-table-column
            prop="status"
            label="案件状态"
            width="120"
        >
          <template #default="{row}">
            <el-tag
                :color="{
                '1': '#909399',
                '2': '#e6a23c',
                '3': '#67c23a',
                '4': '#a9a9a9',
                '5': '#409eff',
                '6': '#5e72e4',
                '7': '#f56c6c'
              }[row.status]"
                effect="dark"
            >
              {{ statusOptions.find(item => item.value == row.status)?.label }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
            prop="caseType"
            label="案件类型"
            width="120"
        >
          <template #default="{row}">
            {{ caseTypeOptions.find(item => item.value == row.caseType)?.label }}
          </template>
        </el-table-column>
        <el-table-column
            prop="createTime"
            label="申请时间"
            width="180"
            sortable
        />
        <el-table-column
            prop="realName"
            label="申请人"
            width="120"
        />
        <el-table-column
            prop="lawyerName"
            label="负责律师"
            width="150"
        />
        <el-table-column
            label="操作"
            width="220"
            fixed="right"
        >
          <template #default="{row}">
            <div class="action-buttons">
              <el-button link type="primary" size="small" @click="viewDetail(row)">
                查看详情
              </el-button>
              <el-button link type="primary" size="small" @click="editCase(row)">
                编辑
              </el-button>
              <el-button link type="danger" size="small" @click="deleteCase(row)">
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
            :current-page="pagination.page"
            :page-size="pagination.size"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            :page-sizes="[10, 20, 50, 100]"
            @size-change="size => { pagination.size = size; handlePaginationChange() }"
            @current-change="page => { pagination.page = page; handlePaginationChange() }"
        />
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.case-list-container {
  padding: 0;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: center;
}

.action-buttons {
  display: flex;
  justify-content: space-around;
}

.action-buttons .el-button {
  padding: 0 8px;
  margin: 0 2px;
  flex: 1;
  text-align: center;
}
</style>